/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package rc;

import java.io.IOException;
import tal.drivechain.plugin.Channel;
import tal.drivechain.plugin.Module;
import tal.drivechain.variable.Variable;
import tal.drivechain.variable.types.DataType;
import tal.remotecanvas.CanvasEventDispatcher;
import tal.remotecanvas.CanvasPacket;
import tal.remotecanvas.CanvasPacket.PACKETType;
import tal.remotecanvas.CanvasPacketReceiver;

/**
 *
 * @author Tal Eisenberg
 */
public class rcModule extends Module implements CanvasPacketReceiver {
    protected ListEventDispatcher eventDispatcher = new ListEventDispatcher();

    @Override
    protected void msgReceived(Variable in, long timestamp, Channel channel) {
        if (in.getDataType().matches(DataType.VAR) && (in.getInternalValue() instanceof CanvasPacket)) {
            eventDispatcher.dispatchEvent((CanvasPacket)in.getInternalValue());
        }
    }

    public void sendCanvasPacket(CanvasPacket packet) throws IOException {
        this.sendToOutputs(packetToVar(packet), -1);
    }

    Variable packetVar = new Variable("tmpName", DataType.VAR, null, true);

    protected Variable packetToVar(CanvasPacket packet) {
        packetVar.setName((packet.type==PACKETType.event?packet.eventId.name():packet.msgId.name()));
        packetVar.setValue(packet, true);
        return packetVar;
    }

    public class ListEventDispatcher extends CanvasEventDispatcher {
        public void dispatchEvent(CanvasPacket event) {
            routePacket(event);
        }
    }

}
